//获取元素
let tbody = document.querySelector("tbody");
let addBtn = document.getElementById("addBtn");
let searchBtn = document.getElementById("searchBtn");
let titleInput = document.getElementsByName("title")[0]; //通过 name 属性获取元素
let urlInput = document.getElementsByName("url")[0];
let keywordInput = document.getElementsByName("keyword")[0];
let searchInput = document.getElementsByName("searchInput")[0];

//发送 AJAX 请求获取网址数据
(() => {
  //简化 url 两个思路
  //1. 默认配置
  //2. 创建实例 发送请求
  let request = axios.create({
    baseURL: "http://127.0.0.1:3000",
  });
  //添加拦截器 简化代码
  request.interceptors.request.use((config) => {
    //显示进度条
    NProgress.start();
    return config;
  });
  request.interceptors.response.use((response) => {
    //隐藏进度条
    NProgress.done();
    return response.data;
  }, err => {
    errorShow('请求失败~~~');
    throw err;
  });

  //初始化请求, 显示网址数据
  async function init() {
    let website = await request.get("/website");
    //插入 tbody
    insertTrs(website);
  }

  //获取数据 并呈现
  init();

  //新增网址
  addBtn.onclick = async function (e) {
    //获取表单元素的值
    let title = titleInput.value;
    let url = urlInput.value;
    let keyword = keywordInput.value;
    //阻止表单的提交行为
    e.preventDefault();
    //发送 AJAX 请求添加数据
    let result = await request.post("/website", {
      title,
      url,
      keyword,
    });
    //将新数据插入到 tbody 中
    insertTr(result);
    //成功提醒
    successShow("添加成功");
  };

  //搜索功能
  searchBtn.onclick = async function () {
    //获取表单元素的值
    let keyword = searchInput.value;
    //发送请求
    let website = await request.get("/website", {
      params: {
        q: keyword,
      },
    });
    //遍历网址数据
    insertTrs(website);
  };

  /**
   * 根据对象创建 tr 并插入 tbody 中
   * @param {*} item
   */
  function insertTr(item) {
    //创建 tr 元素
    let tr = document.createElement("tr");
    //创建第一个 td
    let td = document.createElement("td");
    td.innerHTML = item.id;
    //创建第二个 td
    let td2 = document.createElement("td");
    td2.innerHTML = item.title;
    //创建第三个 td
    let td3 = document.createElement("td");
    td3.innerHTML = item.url;
    //创建第四个 td
    let td4 = document.createElement("td");
    td4.innerHTML = item.keyword;
    //创建第五个 td
    let td5 = document.createElement("td");
    //创建按钮
    let button = document.createElement("button");
    button.innerHTML = "删除";
    button.className = "btn btn-danger btn-sm";
    //为删除按钮绑定单击事件
    button.onclick = async function () {
      //显示确认框
      if (!confirm("您确定要删除当前网址么??")) return;
      //删除当前的网址
      await request.delete("/website/" + item.id);
      //删除当前的 tr
      tbody.removeChild(tr);
      //提醒
      successShow('删除成功')
    };
    //组装结构
    td5.appendChild(button);
    //将所有的 td 插入到 tr
    tr.appendChild(td);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tr.appendChild(td4);
    tr.appendChild(td5);
    //将 tr 插入到 table
    tbody.appendChild(tr);
  }

  /**
   * 将数组中的所有的数据 创建 tr 并插入 tbody
   * @param {*} websiteArr
   */
  function insertTrs(websiteArr) {
    //清空 tbody
    tbody.innerHTML = "";
    //遍历网址数据
    websiteArr.forEach((item) => {
      insertTr(item);
    });
  }

  function successShow(msg) {
    Toastify({
      text: msg,
      duration: 3000,
      destination: "https://github.com/apvarun/toastify-js",
      newWindow: true,
      close: true,
      gravity: "top", // `top` or `bottom`
      position: "center", // `left`, `center` or `right`
      stopOnFocus: true, // Prevents dismissing of toast on hover
      style: {
        background: "linear-gradient(to right, #00b09b, #96c93d)",
      },
      onClick: function () {}, // Callback after click
    }).showToast();
  }

  function errorShow(msg) {
    Toastify({
      text: msg,
      duration: 3000,
      destination: "https://github.com/apvarun/toastify-js",
      newWindow: true,
      close: true,
      gravity: "top", // `top` or `bottom`
      position: "center", // `left`, `center` or `right`
      stopOnFocus: true, // Prevents dismissing of toast on hover
      style: {
        background: "linear-gradient(to right, #c52929, #c52929)",
      },
      onClick: function () {}, // Callback after click
    }).showToast();
  }
})();
